<?php
/**
 * Created by PhpStorm.
 * User: Dave
 * Date: 2018/10/19
 * Time: 11:45
 */

namespace Biz\service\activity;

use Biz\model\activity\AllActivitySku;
use Biz\model\activity\GroupBuy as mGroupBuy;
use Biz\model\activity\GroupBuyGoods as mGroupBuyGoods;
use Biz\model\trade\OrderGoods;
use Biz\module\Classes\OrderGroupBuy;
use Biz\service\Goods as sGoods;
use Biz\service\Goods;
use Biz\validate\activity\GroupBuy as vGroupBuy;
use Biz\service\activity\AllActivityInfo as sAllActivityInfo;
use Biz\model\activity\AllActivityGoods;
use Doraemon\service\User;
use Doraemon\tools\HhzClient;
use Biz\cache\activity\GroupBuy as cGroupBuy;
use Biz\service\Share as sShare;
use Doraemon\tools\Log;
use Doraemon\tools\MiniProgramConfig as tMiniProgramConfig;
use Doraemon\tools\MiniProgramConfig;
use EasyWeChat\Factory;
use Biz\pockets\constInterface\ActivityInfo;
use Biz\service\activity\AllactivityInfoBak;
use Biz\service\Sku as sSku;
/**
 * @deprecated
 */
class GroupBuy
{
    /**
     * 根据拼团id获取拼团详细信息
     * **/
    public static  function getInfoByGroupBuyId($groupBuyId)
    {
        $goodsInfo = [];
        $info = cGroupBuy::getItem($groupBuyId);
        if(!$info) {
            $where = [
                'id' => $groupBuyId,
                'status' => mGroupBuy::STATUS_NORMAL
            ];
            $info = mGroupBuy::getInfo($where);
            if(!$info) {
                throw new \Exception('请求参数异常');
            }
            cGroupBuy::setItem($groupBuyId, $info);
        }

        $goodsInfo = sGoods::Goods($info['goods_id'], sGoods::FIELDS_GROUP_DETAIL, ['activity_type' => ActivityInfo::ACTIVITY_TYPE_TUAN]);
        $goodsInfo['share_info'] = sShare::getGroupBuyShare($groupBuyId);
        $goodsInfo['group_buy_id'] = $info['id'];
        $goodsInfo['min_count'] = $info['min_count'];
        $goodsInfo['current_count'] = $info['current_count'] + $info['add_count'];
        $goodsInfo['start_time'] = strtotime($info['start_time']);
        $goodsInfo['end_time'] = strtotime($info['end_time']);

        return $goodsInfo ? : (object)[];
    }

    public static function increGroupCounter(array $groupIds, $countType = mGroupBuy::COUNT_TYPE_BUYER, $increCounter = 1)
	{
		$groupList = mGroupBuy::getInfos(['id' => $groupIds, 'status' => mGroupBuy::STATUS_NORMAL]);
		$currentTime = date('Y-m-d H:i:s');
		foreach ($groupList as $item) {
			if (! ( $item['start_time'] <= $currentTime && $item['end_time'] >= $currentTime)) {
				throw new \Exception('团购活动还未开始或已结束');
			}
		}
		$rowCounter = mGroupBuy::increCounter(array_column($groupList, 'id'), $countType, $increCounter);
		self::succGroupbuyReminderUser($groupIds);
		return $rowCounter;
	}

	private static function succGroupbuyReminderUser(array $groupIds) {
		$results = self::isGroupSuccess($groupIds, 'reminderUser');
		$succGroupIds =  []; //刚刚拼团成功
		foreach ($results as $groupId => $result) {
			if ($result['status'] == mGroupBuy::STATUS_GROUP_SUCCESS_CURRENT) {
				$succGroupIds[] = $groupId;
			}
		}
		if ($succGroupIds) {
			$orderGoodsInfos = OrderGoods::getInfosByActivityType(AllActivityInfo::ACTIVITY_TYPE_TUAN, $succGroupIds);
			$shopInfos = User::getUsers(array_column($orderGoodsInfos, 'shop_id'));
			foreach($orderGoodsInfos as $orderGoodsInfo) {
				$noticeData = [
					'keyword1' => $orderGoodsInfo['title'],
					'keyword2' => $shopInfos[$orderGoodsInfo['shop_id']]['nick'],
					'keyword3' => $orderGoodsInfo['order_no'],
					'keyword4' => $orderGoodsInfo['pay_amount'],
					'keyword5' => '团购成功，我们会在团购结束后统一发货，请耐心等待。'
				];
				Log::debug('发送成团提醒', ['groupid' => $succGroupIds, 'notice' => $noticeData]);
				OrderGroupBuy::succGroupbuyReminderUser($orderGoodsInfo['order_no'], $noticeData);
			}
			mGroupBuy::update(['is_reminder' => 1], ['id' => $succGroupIds]);
		}
	}

	public static function isGroupSuccess(array $groupIds, $from = 'orderPage')
	{
		$groupList = mGroupBuy::getInfos(['id' => $groupIds, 'status' => mGroupBuy::STATUS_NORMAL], '*', $from == 'reminderUser' ? true : false);
		$groupList = array_column($groupList, null, 'id');
		$currentTime = date('Y-m-d H:i:s');
		$results = [];
		foreach ($groupIds as $groupId) {
			if (isset($groupList[$groupId])) {
				$actualCounter = $groupList[$groupId]['current_count'] + $groupList[$groupId]['add_count'];
				if ($groupList[$groupId]['start_time'] <= $currentTime && $groupList[$groupId]['end_time'] >= $currentTime) {
					$results[$groupId] = mGroupBuy::$status_descs[mGroupBuy::STATUS_NORMAL];
					// 如果是判断是否给用户发送拼团成功消息
					if ($actualCounter >= $groupList[$groupId]['min_count'] && !$groupList[$groupId]['is_reminder'] && $from = 'reminderUser') {
						$results[$groupId] = mGroupBuy::$status_descs[mGroupBuy::STATUS_GROUP_SUCCESS_CURRENT];
					}
				}else if ( $actualCounter >= $groupList[$groupId]['min_count']) {
					$results[$groupId] = mGroupBuy::$status_descs[mGroupBuy::STATUS_GROUP_SUCCESS];
				} else {
					$results[$groupId] = mGroupBuy::$status_descs[mGroupBuy::STATUS_DELECT];
				}
			} else {
				$results[$groupId] = mGroupBuy::$status_descs[mGroupBuy::STATUS_DELECT];
			}
		}
		return $results;
	}

	public static function admSaveGroupBuy($data, $adminuid)
	{
		if (!vGroupBuy::validate($data, 'common')) {
			throw new \Exception(vGroupBuy::firstError());
		}
		$checkGoodsList[$data['goods_id']] = $data['group_buy_price'];
		$checkActivityInfo = [
		    'start_time' => $data['start_time'],
            'end_time' => $data['end_time']
        ];

		// 因为提示语并不是固定的，所以验证价格的操作，不使用验证器
        $result = AllactivityInfoBak::admCheckActivityPrice($checkGoodsList, $checkActivityInfo, AllactivityInfoBak::ACTIVITY_TYPE_TUAN);
        if(end($result)) {
            $invalidPriceData = end($result);
            $skuInfos = sSku::Sku([$data['goods_id']], sSku::FIELDS_GROUP_ALL);
            $skuInfos = array_column($skuInfos[$data['goods_id']]['sku_info'], null, 'sku_id');

            $invalidPriceData = reset($invalidPriceData);
            throw new \Exception('sku ' . $skuInfos[$invalidPriceData['sku_id']]['sku_desc'] . ' 的团购价 ' . $data['group_buy_price'][$invalidPriceData['sku_id']] . ' 高于同时段的商家直降价 ' . $invalidPriceData['activity_price'] . ' ，请修改后再保存');
        }


		$goodsInfo = Goods::Goods([$data['goods_id']], Goods::FIELDS_GROUP_BASE)[$data['goods_id']];
		mGroupBuy::action(function () use ($data, $goodsInfo, $adminuid) {
			$formatData = [
				'id'=> isset($data['groupbuy_id'])? $data['groupbuy_id'] : 0,
				'shop_id'=> $goodsInfo['shop_id'],
				'goods_id'=> $data['goods_id'],
				'start_time'=> $data['start_time'],
				'end_time'=> $data['end_time'],
				'min_count'=> $data['min_count'],
				'group_buy_price'=> $data['group_buy_price'],
			];
			$id  = $formatData['id'] = mGroupBuy::saveData($formatData, $adminuid);

			$skusData = [];
			foreach ($formatData['group_buy_price'] as $skuId => $groupBuyPrice) {
				if ($groupBuyPrice) $skusData[] = [
					'group_buy_id' => $id,
					'shop_id' => $formatData['shop_id'],
					'goods_id' => $formatData['goods_id'],
					'sku_id' => $skuId,
					'group_buy_price' => $groupBuyPrice,
					'start_time' => $formatData['start_time'],
					'end_time' => $formatData['end_time'],
				];
			}
			mGroupBuyGoods::saveData($skusData,$id);
			list($activityGoodsData, $activitySkuData) = self::formatAllAcvivitesData($formatData, $skusData);
			sAllActivityInfo::admUpdateActivityInfo($id, sAllActivityInfo::ACTIVITY_TYPE_TUAN, $activityGoodsData, $activitySkuData, sAllActivityInfo::ALL_ACTIVITY_TYPE_TUAN);
		});

	}

	public static function admDel($groupbuyId) {
		mGroupBuy::action(function () use ($groupbuyId) {
			mGroupBuy::update(['status' => mGroupBuy::STATUS_DELECT], ['id' => $groupbuyId]);
			mGroupBuyGoods::update(['status' => mGroupBuyGoods::STATUS_DELECT], ['group_buy_id' => $groupbuyId]);
			sAllActivityInfo::admDelActivityInfo($groupbuyId, sAllActivityInfo::ACTIVITY_TYPE_TUAN, sAllActivityInfo::ALL_ACTIVITY_TYPE_TUAN);
		});
	}

	private static function formatAllAcvivitesData($goodsDatas, $skuDatas)
	{
		$activityGoodsData[] = [
			'activity_id' => $goodsDatas['id'],
			'shop_id' => $goodsDatas['shop_id'],
			'goods_id' => $goodsDatas['goods_id'],
			'channel' => HhzClient::APPTYPE_TUAN_MINIPROGRAM,
			'type' => sAllActivityInfo::ACTIVITY_TYPE_TUAN,
			'start_time' => $goodsDatas['start_time'],
			'end_time' => $goodsDatas['end_time'],
			'status' => AllActivityGoods::STATUS_NORMAL,
			'preview_start_time' => $goodsDatas['start_time'],
			'real_start_time' => $goodsDatas['start_time'],
			'real_end_time' => $goodsDatas['end_time'],
		];
		$activitySkuData = [];
		foreach ($skuDatas as $skuData) {
			$activitySkuData[]= [
				'activity_id' => $skuData['group_buy_id'],
				'shop_id' => $skuData['shop_id'],
				'type' => sAllActivityInfo::ACTIVITY_TYPE_TUAN,
				'goods_id' => $skuData['goods_id'],
				'sku_id' => $skuData['sku_id'],
				'channel' => HhzClient::APPTYPE_TUAN_MINIPROGRAM,
				'status' => AllActivitySku::STATUS_NORMAL,
				'is_activity_stock' => AllActivitySku::NOT_USE_ACTIVITY_STOCK,
				'activity_stock' => 0,
				'actual_stock' => 0,
				'activity_price' => $skuData['group_buy_price'],
				'is_activity_commission' => AllActivitySku::NOT_USE_COMMISSION,
				'activity_commission' => 0,
				'start_time' => $skuData['start_time'],
				'end_time' => $skuData['end_time'],
				'preview_start_time' => $skuData['start_time'],
				'real_start_time' => $skuData['start_time'],
				'real_end_time' => $skuData['end_time'],
			];
		}
		return [$activityGoodsData, $activitySkuData];

	}

	public static function admGroupBuyList($where ,$page, $pagesize = 20)
	{
		$groupbuyInfos = mGroupBuy::getList($where, $page, $pagesize);
		$count = $groupbuyInfos['count'];
		$groupbuyInfos = $groupbuyInfos['list'];
		$groupBuyGoodsInfos = mGroupBuyGoods::selectByGroupBuyIds(array_column($groupbuyInfos, 'id'));
		$groupBuyStatus = GroupBuy::isGroupSuccess(array_column($groupbuyInfos, 'id'));
		$goodsInfos = Goods::Goods(array_column($groupbuyInfos, 'goods_id'), Goods::FIELDS_GROUP_DETAIL);
		$rst = [];
		foreach ($groupbuyInfos as $groupbuyInfo) {
			$rst[$groupbuyInfo['id']] = $groupbuyInfo;
			$rst[$groupbuyInfo['id']]['goods_info'] = $goodsInfos[$groupbuyInfo['goods_id']];
			$rst[$groupbuyInfo['id']]['goods'] = $groupBuyGoodsInfos[$groupbuyInfo['id']];
			$rst[$groupbuyInfo['id']]['goods']['min_price'] = min( array_column($groupBuyGoodsInfos[$groupbuyInfo['id']], 'group_buy_price'));
			$rst[$groupbuyInfo['id']]['goods']['max_price'] = max( array_column($groupBuyGoodsInfos[$groupbuyInfo['id']], 'group_buy_price'));
			$statusDesc = self::admStatusDesc($groupbuyInfo['start_time'], $groupbuyInfo['end_time'], $groupbuyInfo['id']);
			$rst[$groupbuyInfo['id']]['status_desc'] = $statusDesc['status_desc'];
			$rst[$groupbuyInfo['id']]['groupbuy_status_desc'] = $statusDesc['status_desc'] == '未开始' ? '团购未开始' : $groupBuyStatus[$groupbuyInfo['id']]['status_desc'];
			$rst[$groupbuyInfo['id']]['btn'] = $statusDesc['btn'];
		}
		return ['list' => $rst, 'count' => $count];
	}

	public static function admQrCode($groupId)
	{
		$tmpPath = "/tmp/";
		$filename = "miniprogramer_" . $groupId . ".png";
		if (!file_exists($tmpPath . $filename)) {
            $app = tMiniProgramConfig::getApp(tMiniProgramConfig::APP_NAME_TUANGOU);
			$response = $app->app_code->getUnlimit("group_buy_id=" . $groupId, [
				'page' => 'pages/detail/detail'
			]);
			if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
				$filename = $response->saveAs($tmpPath, $filename);
			}
		}

		return $tmpPath . $filename;
	}


	private static function admStatusDesc($startTime, $endTime, $id) {
		$currentTime = date('Y-m-d H:i:s');
		$statusDesc = ['status_desc' => '', 'btn' => []];
		if ($startTime > $currentTime) {
			$statusDesc['status_desc'] = '未开始';
			$statusDesc['btn'] = [ [
				'title' => '编辑',
				'url' => '/admin/activity/groupbuy/add?groupbuy_id=' . $id,
				'name' => 'edit'
			], [
				'title' => '二维码',
				'url' => '/admin/activity/groupbuy/qrcode?groupbuy_id=' . $id,
				'name' => 'qrcode'
			],[
				'title' => '删除',
				'url' => '/admin/activity/groupbuy/del?groupbuy_id=' . $id,
				'name' => 'del'
			]
			];
		} else if ($startTime < $currentTime && $endTime > $currentTime) {
			$statusDesc['status_desc'] = '进行中';
			$statusDesc['btn'] = [ [
				'title' => '编辑',
				'url' => '/admin/activity/groupbuy/add?groupbuy_id=' . $id,
				'name' => 'edit'
			], [
				'title' => '加 1',
				'url' => '/admin/activity/groupbuy/addcount?groupbuy_id=' . $id,
				'name' => 'addOne'
			], [
				'title' => '二维码',
				'url' => '/admin/activity/groupbuy/qrcode?groupbuy_id=' . $id,
				'name' => 'qrcode'
			], [
				'title' => '查看订单',
				'url' => '/admin/activity/groupbuy/vieworder?groupbuy_id=' . $id,
				'name' => 'viewOrder'

			]
			];
		} else if ($endTime < $currentTime) {
			$statusDesc['status_desc'] = '已结束';
			$statusDesc['btn'] = [ [
				'title' => '查看订单',
				'url' => '/admin/activity/groupbuy/vieworder?groupbuy_id=' . $id,
				'name' => 'viewOrder'

			] ];
		}
		return $statusDesc;
	}
}